package Day2025_02_22;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

public class MyTimer {
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    private Object locker = new Object();
    public MyTimer () {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) locker.wait();
                    }
                    MyTask task = this.queue.take();
                    long currentTime = System.currentTimeMillis();
                    if (currentTime >= task.getTime()) task.getRunnable().run();
                    else {
                        long waitTime = task.getTime() - System.currentTimeMillis();
                        queue.put(task);
                        synchronized (locker){
                            locker.wait(waitTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        // 创建一个后台线程
        Thread daemonThread = new Thread(() -> {
            while (true) {
                // 定时唤醒
                synchronized (locker) {
                    locker.notifyAll();
                }
                // 休眠一会
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        // 设置成后台线程
        daemonThread.setDaemon(true);
        // 启动线程
        daemonThread.start();
    }

    public void schedule(Runnable runnable, long delay) throws InterruptedException {
        // 根据传处的参数，构造一个MyTask
        MyTask task = new MyTask(runnable, delay);
        // 把任务放入阻塞队列
        queue.put(task);
//        System.out.println("添加成功");
        // 唤醒等待的线程
        synchronized (locker) {
            locker.notifyAll();
        }
    }
}


class MyTask implements Comparable<MyTask> {
    private Runnable runnable;
    private long time;
    public MyTask (Runnable runnable, long time) {
        if (runnable == null) throw new IllegalArgumentException("任不能为空");
        if (time < 0) throw new IllegalArgumentException("执行时间不能为负数");
        this.runnable = runnable;
        this.time = time + System.currentTimeMillis();
    }

    public Runnable getRunnable () {
        return runnable;
    }

    public long getTime () {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        if (this.getTime() > o.getTime()) return 1;
        else if (this.getTime() < o.getTime()) return -1;
        else return 0;
    }
}
